/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.ajz.service;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.web.CookieUtils;
import com.jeesite.modules.ajz.dao.AjzHouseInfoDao;
import com.jeesite.modules.ajz.entity.AjzCheck;
import com.jeesite.modules.ajz.entity.AjzFile;
import com.jeesite.modules.ajz.entity.AjzHouseInfo;
import com.jeesite.modules.ajz.entity.AjzRecord;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.utils.ImageUtils;
import com.jeesite.modules.sys.utils.PathUtils;
import com.jeesite.modules.sys.utils.WordUtils;
import com.jeesite.modules.sys.wx.qy.util.DloadImgUtil;
import com.jeesite.modules.sys.wx.qy.util.QyConfigUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 出租屋信息Service
 * @author hhx
 * @version 2019-06-27
 */
@Service
@Transactional(readOnly=true)
public class AjzHouseInfoService extends CrudService<AjzHouseInfoDao, AjzHouseInfo> {

	@Autowired
	private AjzRecordService ajzRecordService;
	@Autowired
	private AjzRecordProcessService ajzRecordProcessService;
	@Autowired
	private EmpUserService empUserService;
	@Autowired
	private AjzCheckService ajzCheckService;
	@Autowired
	private AjzFileService ajzFileService;

	/**
	 * 获取单条数据
	 * @param ajzHouseInfo
	 * @return
	 */
	@Override
	public AjzHouseInfo get(AjzHouseInfo ajzHouseInfo) {
		return super.get(ajzHouseInfo);
	}
	
	/**
	 * 查询分页数据
	 * @param ajzHouseInfo 查询条件
	 * @return
	 */
	@Override
	public Page<AjzHouseInfo> findPage(AjzHouseInfo ajzHouseInfo) {
		return super.findPage(ajzHouseInfo);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param ajzHouseInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(AjzHouseInfo ajzHouseInfo) {
		super.save(ajzHouseInfo);
	}
	
	/**
	 * 更新状态
	 * @param ajzHouseInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(AjzHouseInfo ajzHouseInfo) {
		super.updateStatus(ajzHouseInfo);
	}
	
	/**
	 * 删除数据
	 * @param ajzHouseInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(AjzHouseInfo ajzHouseInfo) {
		super.delete(ajzHouseInfo);
	}

	/**
	 * 获取AjzHouseInfo所有数据
	 */
	public List<AjzHouseInfo> findAllList() {
		return dao.findAllList();
	}

	public AjzHouseInfo getById(String id){
		return  dao.getById(id);
	}

	/**
	 * 根据地址查询出租屋信息
	 * @param addr
	 * @return
	 */
	public List<AjzHouseInfo> findListByAddr(String addr){
		List<AjzHouseInfo> ajzHouseInfos = dao.findListByAddr(addr);
		return ajzHouseInfos;
	}

	//==========================================以下是recordCommit提交的方法,序号代表流程中所在位置=========================================================

	//以下为提交检查记录的封装数据对象,以及保存出租屋基本信息
	@Transactional(readOnly=false)
	public AjzRecord saveCmtRecord(String recordProcessId,AjzHouseInfo ajzHouseInfo, HttpServletRequest request) throws IOException {

		//当前轮次
		String cycleIndex = ajzHouseInfo.getCycleIndex();  //添加时要设置为1

		//创建人信息  TODO 确认下userId是否有问题
		String userId = "system";
		if(StringUtils.isNotBlank(CookieUtils.getCookie(request, "userId"))){
			userId = CookieUtils.getCookie(request, "userId");
		}

		//判断record是否存在，若存在则更新该条数据，否则则插入一条新的数据
		AjzRecord ajzRecord = ajzRecordService.findInfoById(ajzHouseInfo.getId(),request.getParameter("tableType"));
		if (ajzRecord == null) {
			ajzRecord = new AjzRecord();
			ajzRecord.setIsNewRecord(true);
			ajzRecord.setCreateDate(new Date());
			ajzRecord.setUpdateDate(new Date());
			ajzRecord.setCreateBy(userId);
			ajzRecord.setUpdateBy(userId);
		} else {
			ajzRecord.setIsNewRecord(false);
			ajzRecord.setUpdateDate(new Date());
			ajzRecord.setUpdateBy(userId);
		}

		//======== 对传过来的值进行处理储存
		//0.获取责令项
		String[] orderStrs = request.getParameterValues("order");
		String status = "";
		String orders = "";
		if (orderStrs != null) {
			orders = orderStrs.toString();
			status = "2"; //需整改
		}else{
			status = "1"; //待复查
		}

		//1.整改期限
		String deadLine = request.getParameter("deadLine");

		Date deadDate = new Date();
		if (StringUtils.equals("0", deadLine)) {
			status = "3"; //无隐患,闭环结束
			cycleIndex = Integer.parseInt(cycleIndex) + 1 + "";  //
			deadDate = null;
		} else {
			deadDate = DateUtils.addDays(deadDate,Integer.parseInt(deadLine));
		}

		ajzRecord.setCycleIndex(cycleIndex);
		ajzRecord.setCheckStatus(status);
		ajzRecord.setDeadline(deadDate);


		//3.执法人员
		String lawWorker = request.getParameter("lawWorker");
		ajzRecord.setLawWorker(lawWorker);

		//4.陪同人员
		String otherWorker = request.getParameter("otherWorker");
		ajzRecord.setOtherWorker(otherWorker);


		//5.隐患问题 TODO

		StringBuffer str = new StringBuffer();
		String itemCount = "";  //总问题条数

		//5.2 隐患问题状态
		String[] checkStatus = request.getParameterValues("checkStatus");
		String[] problems = request.getParameterValues("problem");

		//message：存值在record表的出租屋消息推送状态
		String messagePush ="0";//默认不推送
		//message：赋值
		for (int i = 0; i < problems.length; i++) {
			if (StringUtils.isNotBlank(problems[i])) {
				//获取问题最高状态值，若存在隐患则为1，表示推送消息
				if("1".equals(checkStatus[i])||"2".equals(checkStatus[i])){
					messagePush ="1" ;
				}
			}
		}
		ajzRecord.setMessagePush(messagePush);


		//6.检查照片
		String[] checkUrl = request.getParameterValues("imgBox1");
		String checkUrls ="";

		//创建保存在文件管理器中的文件路径
		String filePath = PathUtils.getFilePath(ajzHouseInfo.getOffice().getOfficeName(),"出租屋",ajzHouseInfo.getAddr());
		//创建保存数据库的图片路径
		String savePath = PathUtils.getSavePath(request,ajzHouseInfo.getOffice().getOfficeName(),"出租屋",ajzHouseInfo.getAddr());

		if (checkUrl !=null&&checkUrl.length>0) {
			checkUrls = DloadImgUtil.downloadMedias(QyConfigUtil.getAccessToken(),"danger", checkUrl, savePath, filePath);
		}
		ajzRecord.setScenePic(checkUrls);

		//7.隐患点照片
		String[] danUrl = request.getParameterValues("imgBox2");
		String danUrls = "";
		if (danUrl !=null&&danUrl.length>0) {
			danUrls = DloadImgUtil.downloadMedias(QyConfigUtil.getAccessToken(),"danger", danUrl, savePath, filePath);
		}
		ajzRecord.setDangerPic(danUrls);


//    图片中转路径本地


		//8.被检查人签字,签字向左旋转
		String hotelDzqm = request.getParameter("hotelDzqm");

		hotelDzqm = rotatePic(hotelDzqm,filePath, savePath);
		ajzRecord.setContactorSign(hotelDzqm);


		//9.工作人员签字1
		String staffDzqm1 = request.getParameter("staffDzqm");
		staffDzqm1 = rotatePic(staffDzqm1,filePath, savePath);
		ajzRecord.setWorkerSign1(staffDzqm1);

		//10.工作人员签字2
		String staffDzqm2 = request.getParameter("staffDzqm2");
		staffDzqm2 = rotatePic(staffDzqm2,filePath, savePath);
		ajzRecord.setWorkerSign2(staffDzqm2);

		//11.基础表类型
		ajzRecord.setBaseType("house");

		//12.baseid
		ajzRecord.setBaseId(CookieUtils.getCookie(request, "house"));

		//13.文书编号
		ajzRecord.setNumber("企" + (new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date()));

		//14.检查项安监类型
		ajzRecord.setTableType(request.getParameter("tableType"));


		//设置主表的轮数和当前状态
		ajzHouseInfo.setCheckStatus(status);
		ajzHouseInfo.setCycleIndex(cycleIndex);
		save(ajzHouseInfo);
		ajzRecordService.save(ajzRecord);


		//ajzRecord复制一份到过程表
		ajzRecord.setId(recordProcessId);
		ajzRecordProcessService.saveRecord(ajzRecord);

		return ajzRecord;
	}

	private String rotatePic(String sign,String filePath,String savePath) throws IOException {
		String laley = Global.getUserfilesBaseDir("");
		long time;
		if (!StringUtils.isBlank(sign)) {
			sign = DloadImgUtil.GenerateImage(sign, filePath, savePath);
			if (sign.startsWith("|")) {
				sign = sign.substring(1);
				time = Calendar.getInstance().getTimeInMillis();
				Thumbnails.of(laley + sign).scale(0.2f).rotate(-90).outputFormat("png").toFile(laley + savePath + "sign" + time + "" + ".png");
				File file = new File(laley + sign);
				if (file.exists()) {
					FileUtils.deleteFile(laley + sign);
					System.out.println("删除成功");
				}
				sign = "|" + savePath + "sign" + time + "" + ".png";
			}
		}
		return sign;

	}


	@Transactional(readOnly=false)
	public List<AjzCheck> saveCmtCheck(String recordProcessId, HttpServletRequest request) {
		//5.1 隐患问题类型
		String[] dangerTypes = request.getParameterValues("dangerType");

		//5.2 隐患问题状态
		String[] checkStatus = request.getParameterValues("checkStatus");

		//message：存值在record表的出租屋消息推送状态
		String messagePush ="0";//默认不推送

		String[] problems = request.getParameterValues("problem");

		//5.3 将隐患问题批量存储
		List<AjzCheck> ajzChecksList = new ArrayList<>();
		for (int i = 0; i < problems.length; i++) {
			if (StringUtils.isNotBlank(problems[i])) {
				AjzCheck ajzCheck = new AjzCheck();
				ajzCheck.setId(UUID.randomUUID().toString().replaceAll("-", ""));
				ajzCheck.setRecordProcessId(recordProcessId);
				ajzCheck.setProblem(problems[i]);
				ajzCheck.setDangerType(dangerTypes[i]);
				ajzCheck.setStatus("0");
				ajzCheck.setBaseType("house");
				ajzCheck.setTableType(request.getParameter("tableType"));
				ajzCheck.setCheckStatus(checkStatus[i]);
				ajzCheck.preInsert();
				ajzChecksList.add(ajzCheck);

				//获取问题最高状态值，若存在隐患则为1，表示推送消息
				if("1".equals(checkStatus[i])||"2".equals(checkStatus[i])){
					messagePush ="1" ;
				}
			}
		}

		//获取ajzRecordProcess的id存储到ajz_check表里面
		if(ajzChecksList.size()>0){
			ajzCheckService.insertForeach(ajzChecksList);
		}

		return ajzChecksList;

	}
	@Transactional(readOnly=false)
	public void saveCmtFile(AjzRecord ajzRecord, List<AjzCheck> ajzChecksList, AjzHouseInfo ajzHouseInfo, HttpServletRequest request) throws IOException {
		String lawWorker = request.getParameter("lawWorker");

		//=====生成检查文书
		//给word模板赋值
		Map<String, Object> data = new HashMap<String, Object>();
		//给data赋值
		data.put("enterpriseName", ajzHouseInfo.getAddr());
		data.put("addr", ajzHouseInfo.getAddr());
		data.put("legalPerson", ajzHouseInfo.getChargePerson());
		data.put("leTel", ajzHouseInfo.getChargePersonTel());
		data.put("area", "生产车间");
		data.put("startTime",request.getParameter("starTime"));
		data.put("endTime", DateUtils.getDateTime());
		data.put("workers",lawWorker.replace(" ",","));

		//签字赋值
		sign(data,ajzRecord,Global.getUserfilesBaseDir(""));

		data.put("time",DateUtils.formatDate(new Date(),"yyyy年MM月dd日"));
		//获取执法人员的证件号码
		String[] workers = lawWorker.split(" ");

		StringBuffer idNums = new StringBuffer();

		for (int i = 0; i < workers.length; i++) {
			EmpUser empUser = new EmpUser();
			empUser.setRefName(workers[i]);
			//根据姓名查询证件号
			List<EmpUser> list  = empUserService.findList(empUser);
			empUser = list.get(0);
			idNums.append(i == workers.length-1 ? empUser.getPhone()  : empUser.getPhone() + ",");
		}

		data.put("idNums",idNums);

		StringBuffer putProblem = new StringBuffer();
		StringBuffer vacancy = new StringBuffer();
		int count=0;

		//获取隐患项
		List<AjzCheck> orderList = new ArrayList<>();
		for (AjzCheck check: ajzChecksList) {
			count++;
			if(check.getCheckStatus().equals("2")){
				orderList.add(check);
			}
			for (int j = 0; j < (188 - check.getProblem().length() / 2); j++) {
				vacancy.append(" ");
			}
			if(check.getCheckStatus().equals("0")){
				putProblem.append(count+"、"+check.getProblem()+"(已整改)"+vacancy+"<br/>");
			}else if(check.getCheckStatus().equals("3")){
				putProblem.append(count+"、"+check.getProblem()+"(责令已整改)"+vacancy+"<br/>");
			}else{
				putProblem.append(count+"、"+check.getProblem()+vacancy+"<br/>");
			}
		}

		data.put("opinion", putProblem);
		data.put("officeName", ajzHouseInfo.getOffice().getOfficeName());


		//创建保存在文件管理器中的文件路径
		String filePath = PathUtils.getFilePath(ajzHouseInfo.getOffice().getOfficeName(),"出租屋",ajzHouseInfo.getAddr());
		//创建保存数据库的图片路径
		String savePath = PathUtils.getSavePath(request,ajzHouseInfo.getOffice().getOfficeName(),"出租屋",ajzHouseInfo.getAddr());

		//生成检查文书
		//生成.doc文件 .pdf文件 .png文件
		String docName = savePath + WordUtils.exportMillCertificateWord(request,"出租屋","检查文书", data,"check.ftl");

		//保存在保存到对应的实体类
		AjzFile ajzFile = new AjzFile();
		ajzFile.setCheckDoc(docName);
		ajzFile.setCheckPdf(docName.replace("doc","pdf"));
		ajzFile.setCheckPng(docName.replace("doc","png"));


		//判断是否有责令项
		if (orderList.size() > 0) {
			// 给word模板赋值
			Map<String, Object> orderData = new HashMap<String, Object>();
			//给data赋值
			orderData.put("enterpriseName", ajzHouseInfo.getAddr());
			orderData.put("endTime", DateUtils.formatDate(DateUtils.addMinutes(new Date(), 15), "dd日HH时mm分"));
			orderData.put("looker", lawWorker.replace(" ", ","));
			orderData.put("number", "1");
			orderData.put("government", "政府 ");
			orderData.put("court", "法院");

			String laley = Global.getUserfilesBaseDir("");
			//签字赋值
			sign(orderData,ajzRecord,laley);

			orderData.put("examineTime", DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
			orderData.put("idNums1", idNums);
			orderData.put("idNums2", idNums);

			//获取责令项
			StringBuffer orderProblem = new StringBuffer();
			int orderCount = 0;
			for(AjzCheck check : orderList){
				orderCount++;
				for (int j = 0; j < (188 - check.getProblem().length() / 2); j++) {
					vacancy.append(" ");
				}
				orderProblem.append(orderCount+"、"+check.getProblem()+"(责令整改)"+vacancy+"<br/>");
			}
			orderData.put("opinion", orderProblem);
			orderData.put("officeName", ajzHouseInfo.getOffice().getOfficeName());

			//生成责令文书
			//生成.doc文件 .pdf文件 .png文件
			String orderWord = savePath + WordUtils.exportMillCertificateWord(request, "出租屋", "责令文书", orderData, "order.ftl");
			ajzFile.setZhenggaiDoc(orderWord);
			ajzFile.setZhenggaiPdf(orderWord.replace("doc","pdf"));
			ajzFile.setZhenggaiPng(orderWord.replace("doc","png"));
		}


		ajzFile.setRecordProcessId(ajzRecord.getId().toString());
		ajzFile.setBaseId(ajzHouseInfo.getId());
		ajzFile.setTableType(request.getParameter("tableType")); //安全生产类别
		ajzFile.setBaseType("house"); //单位为出租屋


		//生成责令整改文书
		if (ajzRecord != null) {
			List<AjzCheck> ajzChecks = new ArrayList<>();
			StringBuffer aProblem = new StringBuffer();
			int checkCount =0;

			ajzChecks = ajzCheckService.findListByRecordProcessId(ajzRecordProcessService.findForNum(ajzRecord.getNumber()).getId());
			for (AjzCheck ajzCheck : ajzChecks) {
				checkCount++;
				if ("3".equals(ajzCheck.getCheckStatus())) {
					aProblem.append(checkCount+"、"+ajzCheck.getProblem()+"(责令完成)"+"<br/>");
				}else if("4".equals(ajzCheck.getCheckStatus())){
					aProblem.append(checkCount+"、"+ajzCheck.getProblem()+"(责令未完成)"+"<br/>");
				}
			}
			Map<String, Object> abarbeitungData = new HashMap<>();//责令复查

			//给abarbeitungData赋值
			abarbeitungData.put("enterpriseName", ajzHouseInfo.getAddr());
			abarbeitungData.put("secondTime", DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
			abarbeitungData.put("safety","街道");
			abarbeitungData.put("whats","局");
			abarbeitungData.put("num","000");
			abarbeitungData.put("number","1");
			abarbeitungData.put("decide","决定");
			abarbeitungData.put("examineTime", DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
			abarbeitungData.put("idNums1", idNums);
			abarbeitungData.put("idNums2", idNums);


			String laley = Global.getUserfilesBaseDir("");
			//签字
			sign(abarbeitungData,ajzRecord,laley);

			//生成责令整改文书
			//生成.doc文件 .pdf文件 .png文件
			abarbeitungData.put("opinion", aProblem);
			abarbeitungData.put("officeName", ajzHouseInfo.getOffice().getOfficeName());
			if (aProblem.length() > 0) {
				String abarbeitungWord = savePath + WordUtils.exportMillCertificateWord(request, "出租屋", "责令整改文书", abarbeitungData, "abarbeitung.ftl");
				ajzFile.setFuchaDoc(abarbeitungWord);
				ajzFile.setFuchaPdf(abarbeitungWord.replace("doc", "pdf"));
				ajzFile.setFuchaPng(abarbeitungWord.replace("doc", "png"));
			}
		}
		//保存到数据库
		ajzFileService.save(ajzFile);
	}


	//签字赋值
	private Map sign(Map map, AjzRecord ajzRecord, String str){
		map.put("worker", "");
		map.put("oworker", "");
		map.put("sign", "");
		if (StringUtils.isNotBlank(ajzRecord.getWorkerSign1())) {
			map.put("worker", ImageUtils.getImageBase(str + ajzRecord.getWorkerSign1().substring(1)));
		}
		if (StringUtils.isNotBlank(ajzRecord.getWorkerSign2())) {
			map.put("oworker", ImageUtils.getImageBase(str + ajzRecord.getWorkerSign2().substring(1)));
		}
		if (StringUtils.isNotBlank(ajzRecord.getContactorSign())) {
			map.put("sign", ImageUtils.getImageBase(str + ajzRecord.getContactorSign().substring(1)));
		}
		return map;
	}
}